/////////
#include <QtNetwork>

#include "client.h"
#include "connection.h"
#include "peermanager.h"

Client::Client()
{
    peerManager = new PeerManager(this);
    qDebug() << "peerManager->setServerPort(" << server.serverPort() << ")";
    peerManager->setServerPort(server.serverPort());
    qDebug() << "peerManager->startBroadcasting()";
    peerManager->startBroadcasting();

    QObject::connect(peerManager, SIGNAL(newConnection(Connection*)),
                     this, SLOT(newConnection(Connection*)));
    QObject::connect(&server, SIGNAL(newConnection(Connection*)),
                     this, SLOT(newConnection(Connection*)));
}

/*
void Client::sendMessage2(const QString &message)
{
    qDebug() << "sending message 2: " << message;
    qDebug() << "# peers: " << peers.size();
}
*/

void Client::sendMessage(const QString &message)
{
    qDebug() << "Client::sendMessage(message)";

    if (message.isEmpty()) {
        qDebug() << "message.isEmpty()";
        return;
    }

    qDebug() << "peers.values().size() = " << peers.values().size();
    QList<Connection *> connections = peers.values();
    foreach (Connection *connection, connections) {
        qDebug() << "connection->peerName(): " << connection->peerName();
        qDebug() << "connection->peerAddress(): " << connection->peerAddress();
        qDebug() << "connection->peerPort(): " << connection->peerPort();
        connection->sendMessage(message);
        qDebug() << "connection->sendMessage()";
    }
}

QString Client::nickName() const
{
    //return QString(peerManager->userName()) + '@' + QHostInfo::localHostName()
    //       + ':' + QString::number(server.serverPort());
    QString n = QString(peerManager->userName());
    n += '@' + QHostInfo::localHostName() + ':' + QString::number(server.serverPort());
    qDebug() << "Client::nickName() = " << n;
    return n;

}

bool Client::hasConnection(const QHostAddress &senderIp, int senderPort) const
{
    qDebug() << "Client::hasConnection(" << senderIp.toString()
             << "," << senderPort << ")";
    qDebug() << "peers.contains(senderIp) = " << peers.contains(senderIp);

    if (senderPort == -1)
        return peers.contains(senderIp);

    if (!peers.contains(senderIp))
        return false;

    QList<Connection *> connections = peers.values(senderIp);
    foreach (Connection *connection, connections) {
        if (connection->peerPort() == senderPort) {
            qDebug() << "connection->peerPort() == senderPort";
            return true;
        } else {
            qDebug() << "connection->peerPort() != senderPort";
        }
    }

    return false;
}

void Client::newConnection(Connection *connection)
{
     qDebug() << "Client::newConnection";
    connection->setGreetingMessage(peerManager->userName());

    connect(connection, SIGNAL(error(QAbstractSocket::SocketError)),
            this, SLOT(connectionError(QAbstractSocket::SocketError)));
    connect(connection, SIGNAL(disconnected()), this, SLOT(disconnected()));
    connect(connection, SIGNAL(readyForUse()), this, SLOT(readyForUse()));
}

void Client::readyForUse()
{
    Connection *connection = qobject_cast<Connection *>(sender());
    if (!connection || hasConnection(connection->peerAddress(),
                                     connection->peerPort()))
        return;

    connect(connection, SIGNAL(newMessage(QString,QString)),
            this, SIGNAL(newMessage(QString,QString)));
    connect(connection, SIGNAL(newMessage(QString)),
            this, SIGNAL(newMessage(QString)));

    peers.insert(connection->peerAddress(), connection);
    QString nick = connection->name();
    if (!nick.isEmpty())
        emit newParticipant(nick);
}

void Client::disconnected()
{
    if (Connection *connection = qobject_cast<Connection *>(sender()))
        removeConnection(connection);
}

void Client::connectionError(QAbstractSocket::SocketError /* socketError */)
{
    if (Connection *connection = qobject_cast<Connection *>(sender()))
        removeConnection(connection);
}

void Client::removeConnection(Connection *connection)
{
    if (peers.contains(connection->peerAddress())) {
        peers.remove(connection->peerAddress());
        QString nick = connection->name();
        if (!nick.isEmpty())
            emit participantLeft(nick);
    }
    connection->deleteLater();
}
